using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using Microsoft.EntityFrameworkCore;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    public class WorkflowVersionRepository : Repository<WorkflowVersion>, IWorkflowVersionRepository
    {
        public WorkflowVersionRepository(LowCodeDbContext context) : base(context)
        {
        }

        public async Task<List<WorkflowVersion>> GetVersionsAsync(long workflowId)
        {
            return await _context.WorkflowVersions
                .Where(v => v.WorkflowId == workflowId)
                .OrderByDescending(v => v.Version)
                .ToListAsync();
        }

        public async Task<WorkflowVersion?> GetVersionAsync(long workflowId, int version)
        {
            return await _context.WorkflowVersions
                .FirstOrDefaultAsync(v => v.WorkflowId == workflowId && v.Version == version);
        }

        public async Task<int> GetNextVersionNumberAsync(long workflowId)
        {
            var max = await _context.WorkflowVersions
                .Where(v => v.WorkflowId == workflowId)
                .Select(v => (int?)v.Version)
                .MaxAsync();
            return (max ?? 0) + 1;
        }
    }
}
